<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Bed as Beds;
use app\admin\model\Prison;
use app\admin\model\Prisoners;
use app\admin\model\ArctypeMod;
use think\Db;

class Bed extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Beds;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where['title|keywords|description'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create($pid)
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $data['create_time'] = strtotime($data['create_time']);

                $prisoners = new Prisoners();
                $data['pider_id'] = $prisoners->where(['name'=>$data['pider_id']])->value('id');
                if (!$data['pider_id']) {
                    return ajaxReturn('监犯不存在,请重新填写');
                }

                $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
                $data['aid'] = $this->cModel->getLastInsID();
                
                if ($result){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('Prison/index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            $atModel = new Prison();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $arcData = $atModel->where(['id' => $pid])->find();  
            
            $data['pid'] = $arcData['id'];
            $data['create_time'] = date('Y-m-d H:i:s', time());
            
            $this->assign('data', $data);
            
            return $this->fetch('edit');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if (isset($data['create_time'])){
                $data['create_time'] = strtotime($data['create_time']);
            }
            if (isset($data['flag']) || isset($data['litpic'])){
                $data['flag'] = $this->_flag($data['flag'], $data['litpic']);
            }
            $prisoners = new Prisoners();
            $data['pider_id'] = $prisoners->where(['name'=>$data['pider_id']])->value('id');
            if (!$data['pider_id']) {
                return ajaxReturn('监犯不存在,请重新填写');
            }
            $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
            if ($result!==false){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $atModel = new Prison();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $data = $this->cModel->get($id);
            $prisoners = new Prisoners();
            $data['pider_id'] = $prisoners->where(['id'=>$data['pider_id']])->value('name');
            
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $this->cModel->where('id='.$val)->delete();
                    }
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }




    public function import(){
        $file = $this->request->file('imgFile');

        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'files');
            if($info){
                $path = ROOT_PATH . 'public' . DS . 'uploads'.DS.'files'.DS.$info->getSaveName();
            }else{
                // 上传失败获取错误信息
                return ajaxReturn($file->getError());
            }
        }


          ini_set('memory_limit','800M');
          //
          error_reporting(E_ALL);
          /** Include path **/
          set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH.'/PHPExcel/Classes/');
            
          /** PHPExcel */
          vendor('PHPExcel.Classes.PHPExcel');

          /** PHPExcel_IOFactory */
          vendor('PHPExcel/Classes/PHPExcel/IOFactory');

          //vendor('PHPExcel/Classes/PHPExcel/Shape/Date.php');

          //$shared = new \PHPExcel_Shared_Date();

          $objPHPExcel = new \PHPExcel();
          //var_dump($info);ExcelToArray()
          //if ($info['xls']['ext']=='xls') {
          $objReader = \PHPExcel_IOFactory::createReader('Excel5');
          // }else{
          //     $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
          // }
          $objPHPExcel = $objReader->load($path,$encode='utf-8');
          $sheet = $objPHPExcel->getSheet(0);
          $highestRow = $sheet->getHighestRow(); // 取得总行数
          //$highestColumn = $sheet->getHighestColumn(); // 取得总列数
        $arr=array();
        //return ajaxReturn('监舍编号重复');
        for($i=2;$i<=$highestRow;$i++){

            $data=array();
            $data['nubmer']=  $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
            $name = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
            $data['pider_id'] = Db('prisoners')->where('name',$name)->value('id');
            if (!$data['pider_id']) {
               return ajaxReturn('不存在监犯'.$name);
            }
            $data['pid_num']=  $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
            $data['danger']=  $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
            $data['pisition']=  $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
            // $data['sentence']=  $objPHPExcel->getActiveSheet()->getCell("AB".$i)->getValue();

            // $data['contract_start']=  $shared ->ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue());
            // $data['contract_end']=  $shared ->ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue());
            // $data['sex'] = $data['sex']=='男'?1:2;
            // if($pid){
            //   $data['pid'] = $pid;
            // }
            
            //$data['update_time'] = time();
            $arr[] = $data;
        }
        $rs = $this->cModel->insertAll($arr);
        if ($rs) {
            return ajaxReturn(lang('action_success'), url('index'));
        }else{
            return ajaxReturn($this->cModel->getError());
        }

    }

    public function download(){
         ob_end_clean();
         ob_start();
         vendor('PHPExcel/Classes/PHPExcel');
        $cfg_columns = array(
            'id'=>array('name'=>lang('id')),
            'nubmer'=>array('name'=>lang('nubmer')),
            'pider_id'=>array('name'=>lang('pider_id')),
            'pid_num'=>array('name'=>lang('pid_num')),
            'danger'=>array('name'=>lang('danger')),
            'pisition'=>array('name'=>lang('pisition')),
        );
        $dataList = $this->cModel->all();
        foreach ($dataList as $key => $value) {
             $dataList[$key]['pider_id'] = $value->Prisoners->name;
        }
        $list = array();
        foreach ($dataList as $key => $value) {
            $list[] = $value->toArray();
        }

        $filename = 'bed.xls';
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="'.$filename.'"');
        header('Content-Disposition:inline;filename="'.$filename.'"');

        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getActiveSheet(0)->mergeCells('B1:D1');
        $export_time = date('Y-m-d H:i:s');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '导出时间:');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', $export_time);

        $cols = 'A';
        foreach ($cfg_columns as $val){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cols++.'2',$val['name']);
        }

        //第三行, 输出详细数据
        $rows = 3;
        foreach ($list as $fields){
            $cols = 'A';
            //按cfg_column的配置项导出
            foreach ($cfg_columns as $k => $val){
                if(empty( $fields[$k])){
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, 0);
                }else{
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, $fields[$k]);
                }

            } 

            $rows ++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }


}